package xyz.riceball.usercore.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.riceball.framework.core.bean.ApiR;
import xyz.riceball.framework.core.bean.ApiRc;
import xyz.riceball.framework.core.context.UserContext;
import xyz.riceball.framework.core.exception.RiceBallBizWarnException;
import xyz.riceball.framework.core.util.BeanUtils;
import xyz.riceball.usercore.entity.dto.UserDTO;
import xyz.riceball.common.entity.po.LanguagePO;
import xyz.riceball.usercore.entity.po.UserPO;
import xyz.riceball.usercore.entity.po.UserRolePO;
import xyz.riceball.usercore.mapper.UserMapper;
import xyz.riceball.usercore.mapper.UserRoleMapper;
import xyz.riceball.common.service.LanguageService;
import xyz.riceball.usercore.service.UserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户表(User)表服务实现类
 *
 * @author xiaovcloud
 * @since 2022-04-24 20:17:51
 */
@Slf4j
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPO> implements UserService {

    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private LanguageService languageService;

    /**
     * 根据用户名查找用户信息
     *
     * @param username 用户名
     * @return 用户
     */
    @Override
    public UserPO getByUsername(String username) {
        LambdaQueryWrapper<UserPO> wrapper = Wrappers.<UserPO>lambdaQuery();
        wrapper.eq(UserPO::getUsername, username);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public UserDTO getCurrentUser(String token) {
        UserPO user = UserContext.getUser(UserPO.class);
        user.setPassword(null);

        UserDTO userDTO = new UserDTO();
        BeanUtils.copyWithoutNull(userDTO,user);

        LambdaQueryWrapper<LanguagePO> wrapper = Wrappers.<LanguagePO>lambdaQuery();
        wrapper.eq(LanguagePO::getId,user.getLanguage());
        LanguagePO languagePO = languageService.getOne(wrapper);
        userDTO.setLanguageName(languagePO.getName());
        return userDTO;
    }

    @Override
    public boolean add(UserPO userPO) {
        checkUserBeforeDb(userPO);
        BeanUtils.buildAutoField(userPO, true, UserContext.getUserId());
        int insert = getBaseMapper().insert(userPO);
        return insert == 1;
    }

    /**
     * 用户操作前的检测
     *
     * @param userPO
     */
    private void checkUserBeforeDb(UserPO userPO) {
        LambdaQueryWrapper<UserPO> wrapperUsername = Wrappers.<UserPO>lambdaQuery();
        wrapperUsername.eq(UserPO::getUsername, userPO.getUsername());
        List<UserPO> userList = getBaseMapper().selectList(wrapperUsername);
        if (StrUtil.isEmpty(userPO.getId())) {
            //新增用户
            if (userList.size() > 0) {
                log.info("用户名重复，username：{}", userPO.getUsername());
                throw new RiceBallBizWarnException("用户名重复！");
            }
        } else {
            if (userList.size() > 1) {
                log.info("用户名重复，username：{}", userPO.getUsername());
                throw new RiceBallBizWarnException("用户名重复！");
            }
            if (userList.size() == 1) {
                if (!userList.get(0).getId().equals(userPO.getId())) {
                    log.info("用户名重复，username：{}", userPO.getUsername());
                    throw new RiceBallBizWarnException("用户名重复！");
                }
            }
        }
    }

    @Override
    public boolean edit(UserPO userPO) {
        checkUserBeforeDb(userPO);

        UserPO user = getBaseMapper().selectById(userPO.getId());
        BeanUtils.copyWithoutNull(user, userPO);
        BeanUtils.buildAutoField(user, false, UserContext.getUserId());

        int edit = getBaseMapper().updateById(user);
        return edit == 1;
    }

    @Override
    public ApiR<Void> delete(List<String> ids) {
        ApiRc<Void> delete = ApiRc.buildResultCount(ids.size());
        for (String id : ids) {
            try {
                //1。删除用户角色关联
                LambdaQueryWrapper<UserRolePO> wrapperLink = Wrappers.lambdaQuery();
                wrapperLink.eq(UserRolePO::getUserId, id);
                userRoleMapper.delete(wrapperLink);

                //2。删除用户
                getBaseMapper().deleteById(id);

            } catch (Exception e) {
                log.error("删除用户失败，id：{}", id);
            }
        }
        return ApiRc.getResult(delete);
    }

    @Override
    public Page<UserPO> selectPage(Page<UserPO> page, UserPO userPO) {
        LambdaQueryWrapper<UserPO> wrapper = Wrappers.<UserPO>lambdaQuery();
        if (StrUtil.isNotEmpty(userPO.getUsername())){
            wrapper.like(UserPO::getUsername,userPO.getUsername());
        }
        if (StrUtil.isNotEmpty(userPO.getNickname())){
            wrapper.like(UserPO::getNickname,userPO.getNickname());
        }
        if (ObjectUtil.isNotEmpty(userPO.getStatus())){
            wrapper.like(UserPO::getStatus,userPO.getStatus());
        }
        return getBaseMapper().selectPage(page,wrapper);
    }
}

